package com.atguigu.gulimall.ssoclient.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author LaiSanShan
 * @date 2021-08-23
 */
@Controller
public class HelloController {

    @Value("${sso.server.url}")
    String loginUrl;

    @Autowired
    StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    @GetMapping("/employees")
    public String employees(Model model,
                            HttpSession session,
                            @RequestParam(value = "token", required = false) String token) {
        if (!StringUtils.isEmpty(token)) {
            String username = redisTemplate.opsForValue().get(token);
            session.setAttribute("loginUser", username);
        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:" + loginUrl + "?redirect_url=http://client1.com:8081/employees";
        }

        List<Object> list = new ArrayList<>();
        list.add("张三");
        list.add("李四");
        model.addAttribute("list", list);
        return "list";
    }
}
